const cdkService = require('../service/cdk.service')
const userService = require('../service/user.service')
const { v4 } = require('uuid')
const R = require('../utils/R')
const { CDK_EXCHANGE_EXCEPTION, GET_CDK_EXCEPTION, GET_CDK_LIST_EXCEPTION } = require('../error/errorType')

class CdkController {

  // 兑换奖品
  async exchange (ctx, next) {
    try {
      const { id: userId } = ctx.userInfo
      const { cdkCode, oldAmount } = ctx

      let result = await cdkService.exchange(cdkCode, userId)
      if (result.affectedRows) {
        let randomAmount = Math.floor(Math.random() * 100) + 1
        await userService.updateAmount(oldAmount + randomAmount, userId) // 更新用户的余额点数
        ctx.dto = R.ok(`兑换成功, ${randomAmount}点余额已存入您的钱包~`, null)
      } else {
        ctx.dto = R.error(CDK_EXCHANGE_EXCEPTION)
      }
    } catch (err) {
      console.log(err.message)
      return ctx.app.emit('error', new Error(CDK_EXCHANGE_EXCEPTION), ctx)
    }
    await next()

  }

  // 生成兑换码
  async getOne (ctx, next) {
    try {
      const { id: userId } = ctx.userInfo
      let code = v4(), status = 0 // 0-未兑换 1-已兑换 => 失效
      let result = await cdkService.generate(code, status, userId)
      if (result.insertId) {
        ctx.dto = R.ok('生成兑换码成功', { code })
      } else {
        ctx.dto = R.error(GET_CDK_EXCEPTION)
      }
    } catch (err) {
      console.log(err.message)
      return ctx.app.emit('error', new Error(GET_CDK_EXCEPTION), ctx)
    }
    await next()
  }
  // 获取兑换码列表
  async list (ctx, next) {
    try {
      const { id: userId } = ctx.userInfo
      let result = await cdkService.list(userId)
      result.forEach(item => {
        item.statusText = item.status == 0 ? '未使用' : '已使用'
      })
      ctx.dto = R.ok('获取兑换码列表成功', result)
    } catch (err) {
      console.log(err.message)
      return ctx.app.emit('error', new Error(GET_CDK_LIST_EXCEPTION), ctx)
    }
    await next()
  }
}

module.exports = new CdkController()